﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace CMS6Tools.Management
{
    public class TextBoxWriter : TextWriter
    {
        public bool OneLine { get; set; }
        private TextBox textBox;
        private WriteFunc write;
        private WriteFunc writeLine;
        delegate void WriteFunc(string value);

        public TextBoxWriter(TextBox textBox)
        {
            this.textBox = textBox;
            write = Write;
            writeLine = WriteLine;
            OneLine = false;
        }

        public override Encoding Encoding
        {
            get { return Encoding.Unicode; }
        }
        
        public override void Write(string value)
        {
            if (textBox.InvokeRequired)
                textBox.BeginInvoke(write, value);
            else
            {
                if (OneLine)
                    textBox.Clear();
                textBox.AppendText(value);
            }
        }
         
        public override void WriteLine(string value)
        {
            if (textBox.InvokeRequired)
                textBox.BeginInvoke(writeLine, value);
            else
            {
                try
                {
                    if (OneLine)
                        textBox.Clear();
                    textBox.AppendText(value);
                    textBox.AppendText(System.Environment.NewLine);

                }
                catch (Exception exp)
                {
                    if (OneLine)
                        textBox.Clear();

                    textBox.Clear();
                    textBox.AppendText(value);
                    textBox.AppendText(System.Environment.NewLine);
                }
            }
        }
    }

}
